import React, { Component, Fragment } from 'react';
import * as Ant from 'antd';

/**
 * @param filters
 * @param btns
 */
export default class extends Component {

    params = {};

    componentDidMount () {
        for (const filter of this.props.filters) {
            this.params[ filter.dataField ] = filter.props?.defaultValue;
        }
    }

    onFilterChange (filter, newValue) {
        // 先把用户自定义的事件给执行了
        filter.props?.onChange && filter.props?.onChange(newValue);
        // 在表单项onChange时 顺便维护一下组件内部记录的this.params
        this.params[ filter.dataField ] = filter.type === 'Input'
            ? newValue.target.value
            : newValue;
    }

    createFilters () {
        return this.props.filters.map((filter, i) => {
            // 动态渲染组件
            const FormComponent = Ant[filter.type];
            return (
                <Ant.Col span={ 6 } key={ i }>
                    <Ant.Form.Item label={ filter.label }>
                        <FormComponent 
                            // 动态参数
                            { ...filter.props } 
                            // 自定义onChange
                            onChange={ (newValue) => this.onFilterChange.call(this, filter, newValue) } 
                        />
                    </Ant.Form.Item>
                </Ant.Col>
            );
        });
    }

    createBtns () {
        return this.props.btns.map((btn, i) => {
            return (
                <Fragment key={ i }>
                    { !!i && <Ant.Divider type="vertical" /> }
                    {/* btn.name 语义化编程 */}
                    <Ant.Button 
                        { ...btn.props } 
                        onClick={ () => btn.props?.onClick && btn.props?.onClick(this.params) }
                    >
                        { btn.name }
                    </Ant.Button>
                </Fragment>
            );
        });
    }

    render () {
        return (
            <Ant.Form className="filter-group">
                <Ant.Row gutter={ 24 }>
                    { this.createFilters() }
                    <Ant.Col span={ 6 } key="btns">
                        { this.createBtns() }
                    </Ant.Col>
                </Ant.Row>
            </Ant.Form>
        );
    }

}
